package com.basic.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.backend.mapper.ArticleImagesMapper;
import com.basic.backend.model.dto.articles.ArticleQueryRequest;
import com.basic.backend.model.entity.ArticleImages;
import com.basic.backend.model.vo.ArticleVO;
import com.basic.backend.service.ArticleImagesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleImagesServiceImpl extends ServiceImpl<ArticleImagesMapper, ArticleImages>
        implements ArticleImagesService {

    @Resource
    private ArticleImagesMapper articleImagesMapper;

    @Resource
    private UserServiceImpl userService;

    @Override
    public Page<ArticleVO> getArticleImagesPage(ArticleQueryRequest request, HttpServletRequest httpRequest) {
        // 1. 构建统一查询条件
        QueryWrapper<ArticleImages> wrapper = new QueryWrapper<>();

        // 精确查询
        if (request.getArticleId() != null) {
            wrapper.eq("articleId", request.getArticleId());
        }
        if (request.getUserId() != null) {
            wrapper.eq("userId", request.getUserId());
        }

        // 模糊查询
        if (StringUtils.isNotBlank(request.getTitle())) {
            wrapper.like("title", request.getTitle());
        }

        // 状态查询
        if (request.getStatusList() != null && !request.getStatusList().isEmpty()) {
            wrapper.in("status", request.getStatusList());
        }

        // 时间范围
        if (request.getCreateTimeRange() != null) {
            Date start = request.getCreateTimeRange().getStartTime();
            Date end = request.getCreateTimeRange().getEndTime();
            if (start != null && end != null) {
                wrapper.between("createdAt", start, end);
            }
        }

        // 处理排序
        handleSort(wrapper, request.getSortField(), request.getSortOrder());

        // 2. 执行单表分页查询
        Page<ArticleImages> page = new Page<>(request.getCurrent(), request.getSize());
        Page<ArticleImages> resultPage = articleImagesMapper.selectPage(page, wrapper);

        // 3. 转换为VO（直接处理图片数据）
        return (Page<ArticleVO>) resultPage.convert(this::convertToVO);
    }

    // 处理排序逻辑
    private void handleSort(QueryWrapper<ArticleImages> wrapper, String sortField, String sortOrder) {
        Set<String> allowedFields = new HashSet<>(Arrays.asList("title", "createdAt", "updatedAt"));

        if (StringUtils.isNotBlank(sortField) && allowedFields.contains(sortField)) {
            boolean isAsc = (sortOrder != null && sortOrder.equalsIgnoreCase("asc"));
            wrapper.orderBy(true, isAsc, sortField);
        } else {
            // 默认按创建时间降序
            wrapper.orderByDesc("createdAt");
        }
    }

    // 实体转VO（包含图片处理）
    private ArticleVO convertToVO(ArticleImages entity) {
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(entity, vo);

        // 设置作者信息
        vo.setAuthor(userService.getUserVO(entity.getUserId()));

        // 处理图片数据
        vo.setImages(parseImages(entity.getImages()));

        return vo;
    }

    // 解析图片字符串
    private List<String> parseImages(String images) {
        if (StringUtils.isBlank(images)) {
            return Collections.emptyList();
        }
        return Arrays.stream(images.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }
}